package com.hefan.api.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 地理位置查询
 * @author sagagyq
 *
 */
public final class GeocoderUtil {
	
	public static Logger logger = LoggerFactory.getLogger(GeocoderUtil.class);
	
	/**
	 * 用户申请注册的key
	 */
	private static final String ak=DynamicProperties.getApplicationString("geocoder.ak");
	
	/**
	 * 输出格式为json或者xml(默认是json)
	 */
	private static final String output = DynamicProperties.getApplicationString("geocoder.output");
	
	/**
	 * 接口请求域名
	 */
	private static final String domainUrl=DynamicProperties.getApplicationString("geocoder.domainUrl");
	
	/**
	 * 根据location获取城市名
	 * @param location
	 * @return
	 */
	public static String getCityByLocation(String location){
		Map<String,Object> map = new HashMap<String,Object>();
		String returnStr = getUrl(domainUrl+getGeocoderParamString(location));
		
		if(StringUtils.isEmpty(returnStr)){
			map.put("status", 500);
			map.put("err", "请求异常");
			return JSONObject.toJSONString(map);
		}
		JSONObject jsonObject = JSON.parseObject(returnStr);
		Integer status = jsonObject.getInteger("status");
		map.put("status", status);
		if(status==0){
			map.put("city", jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString("city"));
		}else if(status==1){
			map.put("err", "服务器内部错误");
		}else if(status==2){
			map.put("err", "请求参数非法");
		}else if(status==3){
			map.put("err", "权限校验失败");
		}else if(status==4){
			map.put("err", "配额校验失败");
		}else if(status==5){
			map.put("err", "ak不存在或者非法");
		}else if(status==101){
			map.put("err", "服务禁用");
		}else if(status==102){
			map.put("err", "不通过白名单或者安全码不对");
		}else if(status>200 && status<300){
			map.put("err", "无权限");
		}else if(status>300 && status<400){
			map.put("err", "配额错误");
		}
		return JSONObject.toJSONString(map);
	}
	private static String getGeocoderParamString(String location){
		return "?ak="+ak+"&location="+location+"&output="+output;
	}
	
	private static String getUrl(String url){
		String result = null;
		try {
			// 根据地址获取请求
			HttpGet request = new HttpGet(url);
			// 获取当前客户端对象
			HttpClient httpClient = new DefaultHttpClient();
			// 通过请求对象获取响应对象
			HttpResponse response = httpClient.execute(request);
			
			
			// 判断网络连接状态码是否正常(0--200都数正常)
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result= EntityUtils.toString(response.getEntity());
			} 
		} catch (Exception e) {
			logger.error("服务器请求异常！！！");
			e.printStackTrace();
		}
		return result;
	}
}
